package com.gmrz.webauthn.protocol.v1.schema;


import com.gmrz.util.Convert;

import java.util.Arrays;
import java.util.UUID;

public class AAGUID {
    private static final int AAGUID_BYTES_SIZE = 16;
    private static final String AAGUID_REGEX = "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})";
    private static final String AAGUID_REPRESENTATION = "$1-$2-$3-$4-$5";
    private byte[] aaguidBytes;
    private UUID aaguid;

    public AAGUID(String uuidAAGUID) {
        if (uuidAAGUID == null) {
            throw new IllegalArgumentException("Null value provided for uuidAAGUID.");
        } else {
            this.aaguid = UUID.fromString(uuidAAGUID);
            this.aaguidBytes = Convert.fromHex(this.normalize());
        }
    }

    public AAGUID(byte[] aaguidBytes) {
        if (aaguidBytes == null) {
            throw new IllegalArgumentException("Null value provided for aaguidBytes.");
        } else if (aaguidBytes.length != 16) {
            throw new IllegalArgumentException("aaguid should be 16 bytes");
        } else {
            this.aaguidBytes = Arrays.copyOf(aaguidBytes, 16);
            String hexString = Convert.toHex(this.aaguidBytes);
            this.aaguid = UUID.fromString(toUUIDformat(hexString));
        }
    }

    public String toString() {
        return this.aaguid.toString().toLowerCase();
    }

    public String normalize() {
        return this.aaguid.toString().replace("-", "").toLowerCase();
    }

    public static String toUUIDformat(String normalizeAAGUID) {
        if (normalizeAAGUID == null) {
            throw new IllegalArgumentException("Null value provided for normalizeAAGUID");
        } else {
            return normalizeAAGUID.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
        }
    }

    public byte[] getBytes() {
        return Arrays.copyOf(this.aaguidBytes, 16);
    }

    public int hashCode() {
        int result = 31 * 1 + (this.aaguid == null ? 0 : this.aaguid.hashCode());
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (obj == null) {
            return false;
        } else if (this.getClass() != obj.getClass()) {
            return false;
        } else {
            AAGUID other = (AAGUID)obj;
            if (this.aaguid == null) {
                if (other.aaguid != null) {
                    return false;
                }
            } else if (!this.aaguid.equals(other.aaguid)) {
                return false;
            }

            return true;
        }
    }

    public boolean normalizeCompare(String normalizeAAGUID) {
        if (normalizeAAGUID == null) {
            throw new IllegalArgumentException("Null value provided for normalizeAAGUID.");
        } else {
            return this.normalize().equals(normalizeAAGUID.toLowerCase());
        }
    }
}